#pragma once

#include "../comm/log.hpp"
#include "../comm/sqlManager.hpp"

struct Article {
    int article_id;           // 文章唯一标识符
    std::string title;        // 文章标题
    int author_id;            // 文章作者的 user_tb 中的 id
    std::string publish_date; // 文章发布时间 (字符串格式 yyyy-mm-dd hh:mm:ss)
    std::string summary;      // 文章摘要
    std::string content;      // 文章主体内容
    std::vector<std::string> tags;  // 文章标签（可以是一个字符串数组或列表）
    std::string category;     // 文章所属类别
    std::string image_url;    // 文章封面图 URL
    int view_count;           // 浏览量
    int like_count;           // 点赞数量
    int comment_count;        // 评论数量
    int share_count;          // 分享次数
};

class ArticleManager {
private:
    ns_sql::MySQLManager _dbManager;
    std::mutex _mutex;

public:
    ArticleManager(const std::string &host, const std::string &user, const std::string &password, const std::string &dbName) {
        LOG_DEBUG() << host << " " << user << " " << password << " " << dbName;
        if (!_dbManager.openDatabase(host, user, password, dbName)) {
            LOG_ERROR() << "无法打开数据库 " << _dbManager.getErrorMessage();
        }
        LOG_DEBUG() << "初始化文章管理器";
    }

    ~ArticleManager() {
        _dbManager.closeDatabase();
    }

    bool AddArticle(const Article &article) {
        std::unique_lock<std::mutex> lock(_mutex);

        // 将 tags 转换为逗号分隔的字符串
        std::string tags_str;
        for (const auto &tag : article.tags) {
            if (!tags_str.empty()) {
                tags_str += ",";
            }
            tags_str += tag;
        }

        // 构建插入文章的 SQL 语句
        std::string query = "INSERT INTO articles (title, author_id, publish_date, summary, content, tags, category, image_url, view_count, like_count, comment_count, share_count) VALUES ('" +
                            article.title + "', " + std::to_string(article.author_id) + ", '" + article.publish_date + "', '" + article.summary + "', '" +
                            article.content + "', '" + tags_str + "', '" + article.category + "', '" + article.image_url + "', " +
                            std::to_string(article.view_count) + ", " + std::to_string(article.like_count) + ", " + 
                            std::to_string(article.comment_count) + ", " + std::to_string(article.share_count) + ")";

        if (!_dbManager.executeQuery(query)) {
            LOG_ERROR() << "添加文章失败: " << _dbManager.getErrorMessage();
            return false;
        }

        LOG_INFO() << "成功添加文章: " << article.title;
        return true;
    }

    bool DeleteArticle(int article_id) {
        std::unique_lock<std::mutex> lock(_mutex);

        // 构建删除文章的 SQL 语句
        std::string query = "DELETE FROM articles WHERE article_id = " + std::to_string(article_id);

        if (!_dbManager.executeQuery(query)) {
            LOG_ERROR() << "删除文章失败，文章 ID: " << article_id << ", 错误信息: " << _dbManager.getErrorMessage();
            return false;
        }

        LOG_INFO() << "成功删除文章，文章 ID: " << article_id;
        return true;
    }

    bool GetAllArticles(std::vector<Article> &articles) {
        std::unique_lock<std::mutex> lock(_mutex);
        std::string query = "SELECT * FROM articles";
        ns_sql::MySQLManager::MySQLResult result = _dbManager.getResult(query);

        if (!result.next()) {
            LOG_ERROR() << "没有查询到数据或查询失败 " << _dbManager.getErrorMessage();
            return false;
        }

        while (true) {
            try {
                Article article;
                article.article_id = result.getInt(0);
                article.title = result.getString(1).empty() ? "" : result.getString(1);
                article.author_id = result.getInt(2);  // 获取 author_id
                article.publish_date = result.getString(3).empty() ? "" : result.getString(3);
                article.summary = result.getString(4).empty() ? "" : result.getString(4);
                article.content = result.getString(5).empty() ? "" : result.getString(5);
                article.category = result.getString(7).empty() ? "" : result.getString(7);
                article.image_url = result.getString(8).empty() ? "" : result.getString(8);
                article.view_count = result.getInt(9);
                article.like_count = result.getInt(10);
                article.comment_count = result.getInt(11);
                article.share_count = result.getInt(12);

                // 处理 tags 字段
                std::string tags_str = result.getString(6);
                std::vector<std::string> tags;
                size_t pos = 0;
                while ((pos = tags_str.find(',')) != std::string::npos) {
                    tags.push_back(tags_str.substr(0, pos));
                    tags_str.erase(0, pos + 1);
                }
                if (!tags_str.empty()) {
                    tags.push_back(tags_str);
                }
                article.tags = tags;

                articles.push_back(article);
            } catch (const std::exception &e) {
                LOG_ERROR() << "数据处理时出现异常：" << e.what();
                return false;
            }

            if (!result.next()) break;
        }

        return true;
    }

    bool GetArticleById(int article_id, Article &article) {
        std::unique_lock<std::mutex> lock(_mutex);
        std::string query = "SELECT * FROM articles WHERE article_id = " + std::to_string(article_id);
        auto result = _dbManager.getResult(query);

        if (!result.next()) {
            LOG_ERROR() << "未能查询到文章或查询失败: " << _dbManager.getErrorMessage();
            return false;
        }

        try {
            article.article_id = result.getInt(0);
            article.title = result.getString(1).empty() ? "" : result.getString(1);
            article.author_id = result.getInt(2);  // 获取 author_id
            article.publish_date = result.getString(3).empty() ? "" : result.getString(3);
            article.summary = result.getString(4).empty() ? "" : result.getString(4);
            article.content = result.getString(5).empty() ? "" : result.getString(5);
            article.category = result.getString(7).empty() ? "" : result.getString(7);
            article.image_url = result.getString(8).empty() ? "" : result.getString(8);
            article.view_count = result.getInt(9);
            article.like_count = result.getInt(10);
            article.comment_count = result.getInt(11);
            article.share_count = result.getInt(12);

            // 处理 tags 字段
            std::string tags_str = result.getString(6);
            std::vector<std::string> tags;
            size_t pos = 0;
            while ((pos = tags_str.find(',')) != std::string::npos) {
                tags.push_back(tags_str.substr(0, pos));
                tags_str.erase(0, pos + 1);
            }
            if (!tags_str.empty()) {
                tags.push_back(tags_str);
            }
            article.tags = tags;

        } catch (const std::exception &e) {
            LOG_ERROR() << "数据处理时出现异常：" << e.what();
            return false;
        }

        return true;
    }

    bool increaseLikeCount(int article_id) {
        std::unique_lock<std::mutex> lock(_mutex);
        // 构造查询语句以增加点赞数
        std::string query = "UPDATE articles SET like_count = like_count + 1 WHERE article_id = " + std::to_string(article_id);

        // 执行更新语句并检查结果
        bool result = _dbManager.executeQuery(query);
        if (!result) {
            LOG_ERROR() << "增加点赞数失败，文章 ID: " << article_id << ", 错误信息: " << _dbManager.getErrorMessage();
            return false;
        }

        // LOG_DEBUG() << "成功增加点赞数，文章 ID: " << article_id;
        return true;
    }

    bool decreaseLikeCount(int article_id) {
        std::unique_lock<std::mutex> lock(_mutex);
        // 构造查询语句以减少点赞数，确保点赞数不低于 0
        std::string query = "UPDATE articles SET like_count = GREATEST(like_count - 1, 0) WHERE article_id = " + std::to_string(article_id);

        // 执行更新语句并检查结果
        bool result = _dbManager.executeQuery(query);
        if (!result) {
            LOG_ERROR() << "减少点赞数失败，文章 ID: " << article_id << ", 错误信息: " << _dbManager.getErrorMessage();
            return false;
        }

        // LOG_DEBUG() << "成功减少点赞数，文章 ID: " << article_id;
        return true;
    }

    int getLikeCount(int article_id) {
        std::unique_lock<std::mutex> lock(_mutex);
        std::string query = "SELECT like_count FROM articles WHERE article_id = " + std::to_string(article_id);
        ns_sql::MySQLManager::MySQLResult result = _dbManager.getResult(query);
        if (!result.next()) {
            LOG_ERROR() << "未能查询到文章或查询失败: " << _dbManager.getErrorMessage();
        } 
        return result.getInt(0);
    }

    bool increaseViewCount(int article_id) {
        std::unique_lock<std::mutex> lock(_mutex);
        std::string query = "UPDATE articles SET view_count = view_count + 1 WHERE article_id = " + std::to_string(article_id);

        // 执行更新语句并检查结果
        bool result = _dbManager.executeQuery(query);
        if (!result) {
            LOG_ERROR() << "增加浏览量失败，文章 ID: " << article_id << ", 错误信息: " << _dbManager.getErrorMessage();
            return false;
        }

        // LOG_DEBUG() << "成功增加浏览量，文章 ID: " << article_id;
        return true;
    }

    bool addCommentCount(int article_id) {
        std::unique_lock<std::mutex> lock(_mutex);
        std::string query = "UPDATE articles SET comment_count = comment_count + 1 WHERE article_id = " + std::to_string(article_id);

        // 执行更新语句并检查结果
        bool result = _dbManager.executeQuery(query);
        if (!result) {
            LOG_ERROR() << "增加评论数失败，文章 ID: " << article_id << ", 错误信息: " << _dbManager.getErrorMessage();
            return false;
        }

        return true;
    }
};
